package com.xiaozhu.service.Impl;

import com.xiaozhu.mapper.*;
import com.xiaozhu.pojo.DTO.UserDto;
import com.xiaozhu.pojo.Entity.*;
import com.xiaozhu.pojo.VO.UserVo;
import com.xiaozhu.pojo.constant.RoleConstant;
import com.xiaozhu.service.LoginService;
import com.xiaozhu.utils.BaseContext;
//import com.xiaozhu.utils.PermissionScanner;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 朱慧军sky_take_out
 * @version 1.0
 */

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<User> userList() {
        List<User> user = loginMapper.userList();
        log.info("userList:{}", user);

        for (User user1 : user) {
            if (user1.getId() != BaseContext.getThreadId()) {
                user1.setPassword("该用户未授权");
            }
        }
        return user;
    }

    @Override
    public User login(UserDto userDto) {

        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        String password = user.getPassword();

        User user1 = loginMapper.login(user);
        log.info("user1:" + user1);

        if (user1 == null) {
            throw new RuntimeException("该账号不存在，请先注册");
        }

        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user1.getPassword())) {
            throw new RuntimeException("密码错误，请重新输入密码");
        }
        return user1;

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(UserDto userDto) {

        // 插入用户
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        loginMapper.insert(user);

        // 需要将当前用户role
        String roleName = userDto.getRole();
        Role role = Role.builder().name(roleName).build();

        // 判断当前用户在
        Role role1 = roleMapper.getRole(role);
        if (role1 == null) {
            roleMapper.inser(role);
        }

        Integer roleId = role1.getId();
        log.info("当前roleId:{}", roleId);
        Long userId = user.getId();

        // 插入user_role
        UserRole userRole = UserRole.builder().roleId(roleId).userId(userId).build();
        userRoleMapper.inser(userRole);
    }

    /**
     * 设置成管理员
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addAdmin(Long userId) {

        // 添加管理员角色.在role中admin是2
        UserRole userRole = UserRole.builder()
                .roleId(RoleConstant.ADMIN_ID).userId(userId).build();

        userRoleMapper.inser(userRole);

        // 需要将修改的管理员添加进去
        Long threadId = BaseContext.getThreadId();
        User user = User.builder().id(userId).build();
        loginMapper.update(user);


        //先查询管理员权限是否为空，不为空，不需要添加
        // 这个sys_role_permission 只有两个数据 user——》permission; admin——》permission
        List<RolePermission> rolePermission = rolePermissionMapper.select(RoleConstant.ADMIN_ID);
        log.info("角色权限表数据：{}", rolePermission);

        if (rolePermission == null || rolePermission.isEmpty()) {
            List<Permission> list = permissionMapper.list();
            log.info("权限表数据：{}",list);
            for (Permission permission : list) { // 将当前权限依次添加给admin
                rolePermissionMapper.insert(permission.getId(), RoleConstant.ADMIN_ID);
            }
        }

    }

    /**
     * 删除
     * 不要删除 role_permission（因为它和具体用户无关，是全局的角色定义，只和admin和user有关）
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> ids) {
        // 1. 删除用户-角色关联
        userRoleMapper.delete(ids);

        // 2. 删除用户表数据
        loginMapper.delete(ids);
    }

    @Override
    public UserVo info(Long userId) {
        log.info("userId:{}", userId);
        // 1. 查询用户角色关系
        List<UserRole> userRoles = userRoleMapper.selectInfo(userId);
        log.info("userRoles:{}", userRoles);
        // 2. 查询角色信息，并收集到列表
        List<Role> roles = new ArrayList<>();
        log.info("Roles:{}", userRoles);

        for (UserRole userRole : userRoles) {
            List<Role> roleList = roleMapper.selectInfo(userRole.getRoleId());
            if (roleList != null && !roleList.isEmpty()) {
                roles.addAll(roleList);
            }
        }
        // 3. 查询用户信息
        User user = loginMapper.selectInfo(userId);
        

        // 4. 封装 UserVo
        UserVo userVo = UserVo.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles(roles)
                .build();
        return userVo;
    }

}
